package com.usermanage.ServiceImpl;

import com.change.Service.AirSoftService;
import com.usermanage.Mapping.PMOrderMapping;
import com.usermanage.Service.PMOrderService;
import com.usermanage.beanParam.CompanyBean;
import com.usermanage.beanParam.PMOrderBean;
import com.usermanage.dataDao.JpaDao;
import com.usermanage.util.HttpUtil;
import com.usermanage.util.JsonData;
import com.usermanage.util.StaticUtil;
import com.usermanage.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Component
@Service("pmOrderService")
public class PMOrderServiceImpl implements PMOrderService {


    @Resource
    private PMOrderMapping pmOrderMapping;
    @Resource
    private JpaDao jpaDao;

    /**
     * 分页得到订单列表
     *
     * @param key
     * @param page
     * @param limit
     * @return
     */
    @Override
    public List<PMOrderBean> findAllList(String key, String page, String limit) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("SELECT * from pm_order  WHERE 1 = 1  ");
        if (StringUtils.isNotBlank(key)) {
            buffer.append(" and CONCAT(IFNULL(order_code,''),IFNULL(project_name,''),IFNULL(buyer_name,'')) LIKE '%").append(key).append("%'");
        }
        buffer.append(" and order_cancel_status is null");
        buffer.append(" order by order_date desc");
        if(Integer.valueOf(page)>0){
            buffer.append(" limit ").append((Integer.valueOf(page) - 1) * Integer.valueOf(limit)).append(",").append(limit);
        }
        List<PMOrderBean> list = jpaDao.getListByPage(buffer.toString(),PMOrderBean.class);
        return list;
    }

    /**
     * 切页列表查询记录数
     *
     * @param key
     * @return
     */
    @Override
    public int getAllListCount(String key) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("SELECT count(*) from pm_order  WHERE 1 = 1  ");
        if (StringUtils.isNotBlank(key)) {
            buffer.append(" and CONCAT(IFNULL(order_code,''),IFNULL(project_name,''),IFNULL(buyer_name,'')) LIKE '%").append(key).append("%'");
        }
        buffer.append(" and order_cancel_status is null");
        return jpaDao.getListCountByPage(buffer.toString());
    }

    /**
     * 验证订单是否存在
     *
     * @param bean
     * @return
     */
    @Override
    public Boolean isExisit(PMOrderBean bean) {
        Example<PMOrderBean> example = Example.of(bean);
        return pmOrderMapping.exists(example);
    }

    /**
     * 保存一条数据
     *
     * @param bean
     * @return
     */
    @Override
    public PMOrderBean save(PMOrderBean bean) {
        PMOrderBean pmOrderBean = bean;
        return pmOrderMapping.save(pmOrderBean);
    }

    /**
     * 通过订单ID查询订单详情
     *
     * @param order_id
     * @return
     */
    @Override
    public List<PMOrderBean> findAllByOrderId(String order_id) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("SELECT * FROM pm_order where 1=1 and order_id ='").append(order_id).append("'");
        List<PMOrderBean> list = jpaDao.getListByPage(buffer.toString(),PMOrderBean.class);
        return list;
    }

    /**
     * 查询订单状态为审核中的订单列表
     *
     * @return
     */
    public List<PMOrderBean> findAllByAudit() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("SELECT * FROM pm_order where 1=1 and workflow_status !='COMPLETED'");
        List<PMOrderBean> list = jpaDao.getListByPage(buffer.toString(),PMOrderBean.class);
        return list;
    }

    /**
     * 通过订单ID更新订单流程状态
     *
     * @param order_id
     * @return
     */
    @Override
    public JsonData refreshPMOrderStatus(String order_id) {
        List<PMOrderBean> pmOrderBeans = findAllByOrderId(order_id);
        PMOrderBean pmOrderBean = pmOrderBeans.get(0);

        JsonData result = AirSoftService.getOrderHeader(order_id,StaticUtil.environmentEnum);
        if (result == null) {
            return JsonData.fail("PM系统请求失败，请稍后重试");
        }
        try {
            if (result.isRet()) {
                Map pmData = StringUtil.JsonToMap(result.getData().toString());
                if(pmData.get("errorCode").equals("0")){
                    JSONArray json = JSONArray.fromObject(pmData.get("model"));
                    Map row = StringUtil.JsonToMap(json.getString(0));
                    if (row.get("workflow") != null) {
                        Map workflow = StringUtil.JsonToMap(StringUtil.ObjectToJson(row.get("workflow")));
                        pmOrderBean.setWorkflow_status(workflow.get("status").toString());
                    } else {
                        pmOrderBean.setWorkflow_status("");
                    }
                    if (row.get("auditor") != null) {
                        pmOrderBean.setOrder_auditor("true");
                    } else {
                        pmOrderBean.setOrder_auditor("false");
                    }
                    save(pmOrderBean);
                    log.info("订单编号为" + pmOrderBean.getOrder_code() + "的订单状态更新成功");
                    return JsonData.success();
                }else{
                    return JsonData.fail("PM订单查询异常，请查证后重试");
                }
            } else {
                return JsonData.fail("PM系统请求超时，请稍后重试");
            }
        } catch (Exception e) {
            log.error("PM订单详情请求异常：" + e.toString());
            return JsonData.fail("PM系统请求超时，请稍后重试");
        }
    }

    /**
     * PM订单项目列表
     *
     * @return
     */
    @Override
    public List<Map> ProjectListByPM() {
        Set set = new HashSet();
        List<PMOrderBean> projectBeans = findAllList(null, "0", "0");
        for (int i = 0; i < projectBeans.size(); i++) {
            Map map = new HashMap();
            map.put("project_name", projectBeans.get(i).getProject_name());
            set.add(map);
        }
        List<Map> ProjectListByPM = new ArrayList<>(set);
        return ProjectListByPM;
    }

    /**
     * 查询订单状态为审核中的订单列表并每天更新订单状态
     */
    @Scheduled(cron = "0 0 0 * * * ")
    public void refreshPMOrderStatusByDay() {
        log.info("-------------------------------------------开始定时更新审核中的订单状态--------------------------------------");
        List<PMOrderBean> pmOrderBeans = findAllByAudit();
        for (int i = 0; i < pmOrderBeans.size(); i++) {
            refreshPMOrderStatus(pmOrderBeans.get(i).getOrder_id());
        }
        log.info("-------------------------------------------结束定时更新审核中的订单状态--------------------------------------");
    }
}
